txt = open("红楼梦.txt", "r", encoding='gb18030').read()

counts = {}
except_char = '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~\n'
except_char += '，。“”：；·‘’、？！'

for word in txt:
    if word not in except_char:
        counts[word] = counts.get(word, 0) + 1

items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)

print("排序前十的字：")
for i in range(10):
    word, count = items[i]
    print(f"{word:<10}{count:>5}")
print("排序后十的字：")
for i in range(10):
    word, count = items[len(items)-i-1]
    print(f"{word:<10}{count:>5}")
